<template>
  <a-drawer
    :width="500"
    :visible="visible"
    @close="onClose"
    :closable="false"
    :maskStyle="{ background: 'transparent' }"
    :get-container="() => $parent?.$refs?.pipelineConfigRef"
    destroyOnClose
  >
    <template #extra>
      <CloseOutlined class="close-icon cursor-icon" @click="onClose" />
    </template>
    <template #title>
      <div class="title">
        <div>{{ isView ? '详情' : '编辑' }}</div>
        <delete-outlined @click="deleteTask" v-if="!isView" />

        <div class="change-task" @click="changeTask" v-if="!isView">
          <swap-outlined />
          更换任务
        </div>
      </div>
    </template>
    <TaskNameSchemaForm />
    <SchemaForm class="task-form" />
  </a-drawer>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useForm } from '@/components/SchemaForm/index';
import { DeleteOutlined, CloseOutlined, SwapOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash';
import { PipelineOperationTypeCode } from '@/enums/pipelineEnum';

const emit = defineEmits(['delete', 'changeTask']);
const pipelineStore = inject<any>('store');
const route = useRoute();
const isView = computed(() => route.params.type == PipelineOperationTypeCode.info);
const { setFlowChoreographyData } = pipelineStore;
const [SchemaForm, formRef] = useForm({
  disabled: isView.value,
  schemas: [],
});
const [TaskNameSchemaForm, taskNameFormRef] = useForm({
  schemas: [
    {
      field: 'name',
      label: '任务名称',
      component: 'Input',
      labelWidth: 80,
      colProps: {
        span: 24,
      },
      required: true,
    },
  ],
});
const visible = ref();
const taskData = ref<Pipeline.Task>({} as Pipeline.Task);

watch(
  [() => formRef.formModel, () => taskNameFormRef.formModel],
  async ([newVal, taskNameFormData]) => {
    if (!visible.value) return;
    const cloneFlow = cloneDeep(pipelineStore.getFlowChoreographyData);
    setTimeout(async () => {
      try {
        const data = await formRef.validate();
        await taskNameFormRef.validate();
        cloneFlow.forEach((item: Pipeline.Task) => {
          if (item.uuid == taskData.value.uuid) {
            item.isValidateError = false;
            item.params = JSON.stringify(data);
            item.name = taskNameFormData.name;
          }
        });
        setFlowChoreographyData(cloneFlow);
      } catch (e) {
        cloneFlow.forEach((item: Pipeline.Task) => {
          if (item.uuid == taskData.value.uuid) {
            item.isValidateError = true;
            item.params = JSON.stringify(newVal);
            item.name = taskNameFormData.name;
          }
        });
        setFlowChoreographyData(cloneFlow);
      }
    }, 0);
  },
  { deep: true },
);

const onClose = () => {
  visible.value = false;
};
const onOpen = async (data: Pipeline.Task) => {
  visible.value = true;
  taskData.value = data;
  taskNameFormRef.setFieldsValue({ name: data.name });
  formRef.resetSchema(eval(`(${data.schema})`));
  formRef.setFieldsValue(JSON.parse(data.params || '{}'));
};

const deleteTask = () => {
  emit('delete', taskData.value.uuid);
  onClose();
};

const changeTask = () => {
  emit('changeTask', taskData.value);
};

defineExpose({
  onOpen,
  onClose,
});
</script>
<style lang="less" scoped>
.title {
  display: flex;
  align-items: center;
  gap: 8px;
  .change-task {
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: 48px;
    font-size: 14px;
    position: relative;
    color: #2590ff;
    &::before {
      content: '';
      position: absolute;
      left: -24px;
      top: 4px;
      height: 14px;
      border-left: 1px solid #e7eff8;
    }
  }
}
.task-form {
  :deep(.ant-form-item-label > label) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: block;
    width: 100%;
    padding-top: 5px;
  }
}
</style>
